/*
 * @Author: silas 
 * @Date: 2021-03-24 11:02:31 
 * @Last Modified by: silas
 * @Last Modified time: 2021-08-10 11:22:51
 */
<template>
  <div class="clearing">
    <div class="contentTopTitle">
      <div class="fl">
        <div class="title">基础配置计算</div>
      </div>
    </div>
    <el-form :inline="true" :model="form">
      <!-- <el-form-item label="区域" label-width="60px">
                <dx-cascader :area_id.sync="form.areaId" :maxLevel="2" />
            </el-form-item> -->
      <el-form-item label="年度" label-width="60px">
        <el-date-picker v-model="form.year" type="year" size="mini" placeholder="选择年" value-format="yyyy"></el-date-picker>
      </el-form-item>
      <el-form-item label="基础配置总额" label-width="120px">
        <el-input type="number" min="0" size="mini" v-model="form.amount"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="orange" @click="handle_cal()">计算</el-button>
        <el-button size="mini" type="orange" @click="handle_export()">导出</el-button>
        <el-button size="mini" type="primary" @click="handle_save()">保存并提交</el-button>
        <el-button size="mini" @click="$router.push({
                            path: '/budget/circleTabs',
                        })">
          返回
        </el-button>

      </el-form-item>
    </el-form>
    <div class="tableBox">
      <el-table id="table" ref="table" size="mini" :header-cell-style="{ background: '#eef1f6' }" :data="tableData" v-loading="tableLoading" style="width: 100%" border>
        <el-table-column prop="areaName" label="管理单位" width="80" />
        <el-table-column label="地区补贴投资(万)" min-width="120">
          <template slot-scope="scope">
            <span v-if="area.indexOf(scope.row.areaId) >= 0">
              <el-input class="g-input" size="mini" min="0" @input="handle_amount(scope.row)" v-model="scope.row.inputId"></el-input>
            </span>
            <span v-else>
              {{ scope.row.subsidy }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="21年百元投资拉动增量收入(万)" min-width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.areaName !== '合计'">
              <el-input class="g-input" size="mini" min="0" @input="handle_amount_input(scope.row,scope.$index)" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g,'$1')" v-model="scope.row.ldIncrementIncome"></el-input>
            </span>
            <span v-else>
              {{ scope.row.ldIncrementIncome }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="21年百元拉动投资占比" min-width="120" prop="rateLd">

        </el-table-column>
        <el-table-column label="挂钩百元拉动投资额(万)" min-width="120" prop="rateDistribute">

        </el-table-column>
        <el-table-column prop="thisYearBudget" label="本年收入预算(万)" min-width="120" />
        <el-table-column prop="thisYearIncomeRate" label="本年收入预算占比" min-width="120" />
        <el-table-column prop="rateAmount" label="挂钩收入投资额（万元）" min-width="120" />
        <el-table-column prop="picTotalAmount" label="画饼合计(万元)" min-width="120" />
      </el-table>
    </div>
  </div>
</template>

<script>
import { $budgetAPI } from "@/api/";
import { getSessionStorage } from "@/common/js/storage";
import prefixAPI from "@/api/prefixAPI";
import { getCookie } from "@/common/js/cookie";
import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
  name: "record",
  data() {
    return {
      form: {
        year: this.moment().format("yyyy"),
        amount: "",
        ids: "",
      },
      tableData: [],
      tableLoading: false,
      area: ["9", "12", "10", "11"],
    };
  },
  mounted() {
    var that = this;
    // getBasicSettingList
    if (that.$route.query.id) {
      that.getData();
    } else {
      that.getAdd();
    }
  },
  methods: {
    getData() {
      var that = this;

      $budgetAPI.getBasicSettingDetail(
        {
          recordId: that.$route.query.id,
        },
        (res) => {
          console.log(res);
          res.content.data.map((it, i) => {
            // if(area.indexOf(it.areaId) > 0) {
            it["inputId"] = it.subsidy;
            // }
          });
          that.form.amount = res.content.totalAmount;
          that.form.year = res.content.acctYear;
          res.content.data.map((it) => {
            it.thisYearIncomeRate =
              +it.thisYearIncomeRate != 0
                ? it.thisYearIncomeRate + "%"
                : it.thisYearIncomeRate;
          });
          that.tableData = res.content.data;
          that.tableLoading = false;
        }
      );
    },
    getAdd() {
      var that = this;

      $budgetAPI.getBasicSettingList(
        {
          acctYear: that.form.year,
          basicTotalAmount: "",
          updateAmoutStr: "",
          ldAmountStr: "",
        },
        (res) => {
          console.log(111, res);
          if (res && res.code == 0) {
            res.content.data.map((it, i) => {
              it["inputId"] = it.subsidy;
            });
            that.tableData = res.content.data;
            that.form.amount = res.content.totalAmount;
            that.form.year = res.content.acctYear;
          }
          that.tableLoading = false;
        }
      );
    },
    getCal(type) {
      var that = this,
        area = ["9", "12", "10", "11"],
        param = [],
        ldAmountStrParam = [];

      if (+that.tableData.slice(-1)[0].subsidy > +that.form.amount) {
        that.$message({
          type: "error",
          message: "补贴总和不得大于基础配置总额",
        });
        return false;
      }
      that.tableData.map((it) => {
        if (area.indexOf(it.areaId) >= 0) {
          var obj = {};
          obj[it.areaId] = it.inputId;
          param.push(obj);
        }
      });
      that.tableData.map((it) => {
        if (it.ldIncrementIncome >= 0 && it.areaName !== "合计") {
          var obj = {};
          obj[it.areaId] = it.ldIncrementIncome;
          ldAmountStrParam.push(obj);
        }
      });
      that.tableLoading = true;
      if (type == "cal") {
        $budgetAPI.getBasicSettingList(
          {
            acctYear: that.form.year,
            basicTotalAmount: that.form.amount,
            updateAmoutStr: JSON.stringify(param),
            ldAmountStr: JSON.stringify(ldAmountStrParam),
          },
          (res) => {
            if (res && res.code == 0) {
              res.content.data.map((it, i) => {
                it["inputId"] = it.subsidy;
              });
              that.tableData = res.content.data;
              that.form.amount = res.content.totalAmount;
            } else {
              that.$message.error(res.message);
            }
            that.tableLoading = false;
          }
        );
      } else {
        $budgetAPI.getBasicSettingSave(
          {
            acctYear: that.form.year,
            basicTotalAmount: that.form.amount,
            updateAmoutStr: JSON.stringify(param),
            ldAmountStr: JSON.stringify(ldAmountStrParam),
          },
          (res) => {
            if (res && res.code == 0) {
              that.$message({
                type: "success",
                message: "保存成功!",
              });
              that.$router.push({
                path: "/budget/circleTabs",
              });
            } else {
              that.$message.error(res.message);
            }
            that.tableLoading = false;
          }
        );
      }
    },
    handle_save() {
      this.getCal("save");
    },
    handle_cal() {
      this.getCal("cal");
    },
    handle_amount_input(row, index) {
      console.log(row.ldIncrementIncome);
      var that = this,
        sum = 0;
      if (+row.ldIncrementIncome < 0) {
        that.$message({
          type: "error",
          message: "21年百元投资拉动增量收入金额需大于0",
        });
        return false;
      }
      that.tableData.map((it) => {
        if (it.ldIncrementIncome != 0 && it.areaName !== "合计") {
          sum += +it.ldIncrementIncome;
        }
      });
      that.tableData.slice(-1)[0].ldIncrementIncome = sum;
    },
    handle_amount(it) {
      var that = this,
        sum = 0;

      if (+it.inputId < 0) {
        that.$message({
          type: "error",
          message: "补贴金额需大于0",
        });
        return false;
      }
      that.tableData.map((it) => {
        console.log(it.inputId);
        if (it.areaId != 0) {
          sum += +it.inputId;
        }
      });
      that.tableData.slice(-1)[0].subsidy = sum;
      console.log(sum);
    },
    handle_export() {
      var xlsxParam = {
        raw: true,
      }; //转换成excel时，使用原始的格式，这样导出的时候数字过长不会变成科学计数法
      let workbook = XLSX.utils.book_new();
      let ws1 = XLSX.utils.table_to_sheet(
        document.querySelector("#table"),
        xlsxParam
      );
      XLSX.utils.book_append_sheet(workbook, ws1, "基础配置计算");
      let wbout = XLSX.write(workbook, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      if (!this.tableData.length) {
        this.$message.error("暂无数据可导出");
        return false;
      }
      this.loading = this.$loading({
        lock: true,
        text: "正在",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], {
            type: 'application/octet-stream;charset=utf-8"',
          }),
          "基础配置计算.xlsx"
        );
        this.loading.close();
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbOut);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.g-input {
  width: 100%;
}

/deep/.el-input--mini .el-input__inner {
  text-align: center;
}
</style>